package com.mediacloud.app.newsmodule.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.mediacloud.app.assembly.util.Utility.getScreenWidth
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.fragment.baoliao.api.MemberApi
import com.mediacloud.app.newsmodule.model.ServiceDetailMode
import com.mediacloud.app.user.utils.RxUtils
import com.utils.DisplayUtil
import kotlinx.android.synthetic.main.activity_service_detail_layout.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

class ServiceDetailActivity : BaseBackActivity() {

    private val id: Int by lazy {
        intent.getIntExtra("id", 0)
    }

    private var serviceData: ServiceDetailMode? = null

    override fun getLayoutResID(): Int {
        return R.layout.activity_service_detail_layout
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initWeb()
        initStateView()
        getCategory()
        apply.setOnClickListener {
            WebViewPageActivity.start(serviceData?.data?.name, serviceData?.data?.link, this)
        }
    }

    private fun initWeb() {
        mWebBrowser.settings.setSupportZoom(true)
        mWebBrowser.settings.builtInZoomControls = true
        mWebBrowser.settings.displayZoomControls = false
        mWebBrowser.settings.useWideViewPort = true
        mWebBrowser.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
                if (mWebBrowser.canGoBack()) {
                    mWebBrowser.goBack()
                    return@OnKeyListener true
                }
            }
            false
        })
    }

    @SuppressLint("CheckResult")
    private fun getCategory() {

        MemberApi.getMemberApi()
            .getServiceDetail(id)
            .compose(
                TransUtils.fastJSonTransform(
                    ServiceDetailMode::class.java
                )
            )
            .compose(RxUtils.schedulersTransformer())
            .subscribe(
                {
                    serviceData = it
                    closeStateView()
                    Log.w("APPTAG", "$it")
//                    var content = it.data.content.replace("<img", "<img style="max-width:100%;height:auto");

                    mWebBrowser.loadDataWithBaseURL(
                        null,
                        getNewData(it.data.content),
                        "text/html",
                        "UTF-8",
                        "about:blank"
                    );

                    setTitle(it.data.name)
                    if (!TextUtils.isEmpty(it.data.linkName)) {
                        apply.visibility = View.VISIBLE
                        apply.text = it.data.linkName
                    } else {
                        apply.visibility = View.GONE
                    }
                },
                {
                    Log.w("APPTAG", "$it")
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }
            )

    }

    /**
     * 设置img标签下的width为手机屏幕宽度，height自适应
     *
     * @param data html字符串
     * @return 更新宽高属性后的html字符串
     */
    private fun getNewData(data: String): String? {
        val document: Document = Jsoup.parse(data)
        val pElements: Elements = document.select("p:has(img)")
        for (pElement in pElements) {
            pElement.attr("style", "text-align:center")
            pElement.attr(
                "max-width",
                (getScreenWidth(this).toString() + "px").toString()
            )
                .attr("height", "auto")
        }
        val imgElements: Elements = document.select("img")
        for (imgElement in imgElements) {
            //重新设置宽高
            imgElement.attr("max-width", "100%")
                .attr("height", "auto")
            imgElement.attr("style", "max-width:100%;height:auto")
        }
        Log.i("newData:", document.toString())
        return document.toString()
    }
    override fun getContent_show_top_color(): String? {
        top.setBackgroundColor(Color.WHITE)
        return "#333333"
    }

    override fun getStatusBarColor(): Int {
        return Color.WHITE
    }
}